package cn.flyboy.utils;

import cn.flyboy.entity.Answer;
import cn.flyboy.entity.the_answer;
import org.apache.poi.hssf.usermodel.*;

import javax.servlet.ServletOutputStream;
import java.util.List;

public class ExcleUtils {
    public static void export(String[] titles, String SheetName, ServletOutputStream out, String name, List<the_answer> lists) throws Exception {
        try {
            // 第一步，创建一个workbook，对应一个Excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();

            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet hssfSheet = workbook.createSheet(SheetName);

            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = hssfSheet.createRow(0);

            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle hssfCellStyle = workbook.createCellStyle();

            // 表头
            HSSFCell hssfCell = null;
            for (int i = 0; i < titles.length; i++) {
                hssfCell = row.createCell(i);//列索引从0开始
                hssfCell.setCellValue(titles[i]);//列名1
                hssfCell.setCellStyle(hssfCellStyle);//列居中显示
            }

            // 第五步，写入实体数据
            for (int i = 0; i < lists.size(); i++) {
                row = hssfSheet.createRow(i + 1);
                the_answer answer = lists.get(i);

                // 第六步，创建单元格，并设置值
                int num = i + 1;
                row.createCell(0).setCellValue(num);

                String Sno = null;
                if (answer.getStu_id() != null) {
                    Sno = answer.getStu_id();
                }
                row.createCell(1).setCellValue(Sno);

                String StuName = null;
                if (answer.getStu_name() != null) {
                    StuName = answer.getStu_name();
                }
                row.createCell(2).setCellValue(StuName);

                String StuClass = null;
                if (answer.getStu_name() != null) {
                    StuClass = answer.getStu_class();
                }
                row.createCell(3).setCellValue(StuClass);

                row.createCell(4).setCellValue(name);

                String fileName = "";
                if (answer.getFile_name() != null) {
                    fileName = answer.getFile_name();
                }
                row.createCell(5).setCellValue(fileName);

                String times = "";
                if (answer.getTimes() != null) {
                    times = answer.getTimes();
                }
                row.createCell(6).setCellValue(times);
            }

            // 第七步，将文件输出到客户端浏览器
            try {
                workbook.write(out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("导出信息失败！");
        }
    }


}
